package com.own.business.resource.module.huawei;

import com.obs.services.ObsClient;
import com.obs.services.model.HttpMethodEnum;
import com.obs.services.model.TemporarySignatureRequest;
import com.own.business.resource.core.base.AbstractObjectStoreUtil;
import com.own.business.resource.core.model.SignatureModel;
import com.own.business.resource.core.model.base.BaseUploadModel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;

/**
 * HuaWeiObsUtil
 *
 * @author chenxueli
 * @date 2023-07-12 09:10:02
 */
@Slf4j
public class HuaWeiObsUtil extends AbstractObjectStoreUtil {

    /**
     * 上传单个文件
     *
     * @param file 文件信息
     * @return 文件存储对象信息
     */
    @Override
    public BaseUploadModel uploadFile(BaseUploadModel file) {
        var client = getObsClient();
        try {
            upload(client, file);
        } finally {
            try {
                client.close();
            } catch (IOException e) {
                log.error("客户端关闭异常");
            }
        }
        return file;
    }

    /**
     * 上传单个文件
     *
     * @param fileList 文件信息列表
     * @return 文件存储对象信息列表
     */
    @Override
    public List<BaseUploadModel> uploadFile(List<BaseUploadModel> fileList) {
        var client = getObsClient();
        try {
            fileList.parallelStream().forEach(file -> upload(client, file));
        } finally {
            try {
                client.close();
            } catch (IOException e) {
                log.error("客户端关闭异常");
            }
        }
        return fileList;
    }

    /**
     * 验证配置是否正常
     *
     * @return 是否正常
     */
    @Override
    public boolean check() {
        var properties = super.getProperties();
        var name = super.getName();
        boolean flag = true;
        if (StringUtils.isEmpty(properties.getKey())) {
            log.error("资源管理{}:华为云obs key填写为空", name);
            flag = false;
        }
        if (StringUtils.isEmpty(properties.getSecret())) {
            log.error("资源管理{}:华为云obs secret填写为空", name);
            flag = false;
        }
        if (StringUtils.isEmpty(properties.getBucket())) {
            log.error("资源管理{}:华为云obs bucket填写为空", name);
            flag = false;
        }
        if (StringUtils.isEmpty(properties.getEndPoint())) {
            log.error("资源管理{}:华为云obs end-point填写为空", name);
            flag = false;
        }
        if (StringUtils.isEmpty(properties.getPosition())) {
            log.error("资源管理{}:华为云obs position填写为空", name);
            flag = false;
        }
        return flag;
    }

    /**
     * 获取上传文件签名
     *
     * @param uri 资源路径
     * @return 签名对象
     */
    @Override
    public SignatureModel signature(String uri) {
        var properties = super.getProperties();
        // 设置文件夹名称
        var host = "https://" + properties.getBucket() + "." + properties.getEndPoint();
        // 创建ObsClient实例
        var client = getObsClient();
        // URL有效期，3600秒
        var expireSeconds = 3600L;
        var headers = new HashMap<String, String>(4);
        headers.put("Content-Type", "text/plain");
        var request = new TemporarySignatureRequest(HttpMethodEnum.PUT, expireSeconds);
        request.setBucketName(properties.getBucket());
        request.setObjectKey(uri);
        request.setHeaders(headers);
        var response = client.createTemporarySignature(request);
        try {
            client.close();
        } catch (IOException e) {
            log.error("客户端关闭异常");
        }
        return SignatureModel.builder()
                .host(host)
                .dir(uri)
                .signature(response.getSignedUrl())
                .type("huawei")
                .build();
    }

    /**
     * 获取obs客户端
     *
     * @return obs客户端
     */
    public ObsClient getObsClient() {
        var properties = super.getProperties();
        return new ObsClient(properties.getKey(), properties.getSecret(), "https://" + properties.getEndPoint());
    }

    /**
     * 上传文件到服务器
     *
     * @param obs  obs客户端
     * @param file 文件
     */
    public void upload(ObsClient obs, BaseUploadModel file) {
        var properties = super.getProperties();
        obs.putObject(properties.getBucket(), file.getFolder("/") + "/" + file.getFileName(), file.getInputStream());
    }

}
